#include "DirectoryEntry.h"

DirectoryEntry::DirectoryEntry (int inode, const char* newFileName) :
	iNodeNum(inode) {
	int i=0;
	//const char* file = newFileName.c_str();
	while(i<12 && newFileName[i]!=0) {
		fileName[i] = newFileName[i];
		i++;
	}
	fileName[i] = 0;
}
DirectoryEntry::~DirectoryEntry() {}
char* DirectoryEntry::getFileName() {
	return fileName;
}
int DirectoryEntry::getINodeNum() {
	return iNodeNum;
}

void DirectoryEntry::parseIntoCharArr(char* buf) {
	/*
	ostringstream stream;
	stream << iNodeNum;
	string iNodeNumString = stream.str();
	cout << iNodeNumString << endl;
	*/
	char str[4];
	sprintf(str,"%d",iNodeNum);
	//cout << str << endl;
	string iNodeNumString(str);


	//char* parsedIodeInfo = padInodenum(iNodeNumString);
	char parsedIodeInfo[4];
	intToByte(iNodeNum, parsedIodeInfo, 0);

	//cout << iNodeNumInBytes << endl;

	//cout << parsedIodeInfo << endl;

	for (int i=0; i<4; i++) {
		//cout << parsedIodeInfo[i];
		buf[i] = parsedIodeInfo[i];
	}

	//strncpy(parsedFileInfo, parsedIodeInfo, 4);

	//cout << buf << endl;
	//cout << fileName << endl;
	int i=4;
	while (fileName[i-4] != 0) {
		buf[i] = fileName[i-4];
		i++;
	}

	for (int j=i; j<16; j++) {
		buf[j] = 0;
	}

	//strncpy(parsedFileInfo+4,fileName,12);
	/*
	stream << iNodeNum;
	ostringstream stream;
	string iNodeNumString = stream.str();
	const char* parsedIodeInfo = iNodeNumString.c_str();
	for (int i=12; i<16; i++) {
		parsedFileInfo[i] = parsedIodeInfo[i-12];
	}*/
	//delete(parsedIodeInfo);
	//cout << buf << endl;
}

char* DirectoryEntry::padInodenum(string inodeNum) {
	//TODO delete somewhere else
	char* paddedNum = new char(4);
	if (inodeNum.size()<4) {
		for (int i=0; i<4-(int)inodeNum.size(); i++) {
			paddedNum[i]='0';
		}
		for (int i=4-inodeNum.size(); i<4; i++) {
			paddedNum[i] = inodeNum[4-i-inodeNum.size()];
		}
	} else {
		for (int i=0; i<4; i++) {
			paddedNum[i] = (unsigned char)inodeNum[i];
		}
	}
	//cout << paddedNum << endl;
	return paddedNum;
}
void DirectoryEntry::intToByte(int val, char* pBytes, int start) {
	pBytes[0+start] = (unsigned char)val;
	pBytes[1+start] = (unsigned char)(val >> 8);
	pBytes[2+start] = (unsigned char)(val >> 16);
	pBytes[3+start] = (unsigned char)(val >> 24);
}
